/**
 * 
 */
package edu.njit.hz278.controller.inpatient;

import java.util.List;

import edu.njit.hz278.bean.AdmittedTo;
import edu.njit.hz278.bean.ClinicBed;
import edu.njit.hz278.controller.Constants;
import edu.njit.hz278.core.db.IQuery;
import edu.njit.hz278.core.db.Query;
import edu.njit.hz278.core.web.Get;
import edu.njit.hz278.core.web.ModelView;
import edu.njit.hz278.core.web.Param;

/**
 * @author Rivers Zhang
 * 
 */
public class Bed {

	private static final IQuery<ClinicBed> bed = new Query<>(ClinicBed.class);
	private static final IQuery<AdmittedTo> admit = new Query<>(
			AdmittedTo.class);

	@Get
	public List<ClinicBed> availBed() {
		StringBuilder sql = new StringBuilder();
		sql.append("SELECT * FROM clinic_bed b WHERE NOT EXISTS ").append(
				"(SELECT * FROM admitted_to a WHERE a.bedId = b.bedId)");
		return bed.getBySQL(sql.toString());
	}

	@Get
	public ModelView assign(
			@Param(value = "admit", forceValid = true) AdmittedTo admitted,
			ModelView mv) {
		if (admitted.getDateIn() == 0)
			admitted.setDateIn(System.currentTimeMillis());

		AdmittedTo record = admit.getByKeys(new String[] { "pNum", "bedId" },
				new Object[] { admitted.getpNum(), admitted.getBedId() });

		if (record != null)
			mv.put(Constants.MSG, Constants.MSG_OOPS);
		else {
			admit.insert(admitted);
			mv.put(Constants.MSG, Constants.MSG_OK);
		}
		return mv;
	}

	@Get
	public ModelView rm(@Param("pNum") int pNum, @Param("bedId") int bedId,
			ModelView mv) {
		int affected = admit.delete(new String[] { "pNum", "bedId" },
				new Object[] { pNum, bedId });
		mv.put(Constants.MSG, affected == 1 ? Constants.MSG_OK
				: Constants.MSG_OOPS);
		return mv;
	}
}
